﻿using System.IO;
using System.Xml;
using Microsoft.Deployment.WindowsInstaller;

namespace UnigyLyncAddinSetupCustomActions
{
	public class WriteXmlConfigCustomAction
	{
		private static readonly string SERVER_IP_PROPERTY = "SERVER_IP";
		private static readonly string SERVER_PORT_PROPERTY = "SERVER_PORT";
		private static readonly string SERVER_SECURE_CONNECTION_PROPERTY = "SERVER_SECURE_CONNECTION";
		private static readonly string CONFIG_FILENAME_PROPERTY = "CONFIG_FILENAME";
		private static readonly string CONFIG_NODE_NAME = "appSettings";
		private static readonly string CONFIG_SUBNODE_NAME = "add";
		private const string IpAttrName = "SERVERIP";
		private const string PortAttrName = "SERVERPORT";
		private const string SecureConnectionAttrName = "ISSECURECONNECTION";

		[CustomAction]
		public static ActionResult WriteXmlConfig(Session session)
		{
			session.Log("Begin WriteXmlConfig");

			bool needSaveModifications = false;
			var actionData = session.CustomActionData;
			var xmlFile = actionData[CONFIG_FILENAME_PROPERTY];
			session.Log("ActionData: {0}", actionData);

			session.Log("WriteXmlConfig - XmlConfig: {0}. Exists: {1}", xmlFile, File.Exists(xmlFile));

			if (File.Exists(xmlFile))
			{
				var doc = new XmlDocument();
				doc.Load(xmlFile);

				XmlNode root = doc.DocumentElement;

				if (root != null)
				{
					XmlNodeList adds = root.SelectNodes(string.Format(".//{0}/{1}", CONFIG_NODE_NAME, CONFIG_SUBNODE_NAME));
					if (adds != null && adds.Count > 0)
					{
						foreach (XmlNode add in adds)
						{
							if (add.Attributes != null && add.Attributes.Count > 0)
							{
								var key = add.Attributes["key"].Value.ToUpperInvariant();
								switch (key)
								{
									case IpAttrName:
										add.Attributes["value"].Value = actionData[SERVER_IP_PROPERTY];
										needSaveModifications = true;
										break;
									case PortAttrName:
										add.Attributes["value"].Value = actionData[SERVER_PORT_PROPERTY];
										needSaveModifications = true;
										break;
									case SecureConnectionAttrName:
										add.Attributes["value"].Value = actionData[SERVER_SECURE_CONNECTION_PROPERTY] == "1" ? "true" : "false";
										needSaveModifications = true;
										break;
								}
							}
						}
					}
				}

				if (needSaveModifications)
				{
					doc.Save(xmlFile);
					session.Log("File: {0} saved.", xmlFile);
				}
			}
			session.Log("WriteXmlConfig - Result: {0}: {1}. {2}: {3}. {4}: {5}",
										  SERVER_IP_PROPERTY,
										  actionData[SERVER_IP_PROPERTY],
										  SERVER_PORT_PROPERTY,
										  actionData[SERVER_PORT_PROPERTY],
										  SERVER_SECURE_CONNECTION_PROPERTY,
										  actionData[SERVER_SECURE_CONNECTION_PROPERTY]);
			return ActionResult.Success;
		}
	}
}
